package com.longrise.filedownloader.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;

import java.util.ArrayList;

/**
 * Created by xkj on 16/4/13.
 * 数据库的crud
 */
public class DBDAO {

    private final SQLiteHelper mDbHelper;
    private SQLiteDatabase mDb;
    private String mDefaultUserid = "downloader";
    private int doSaveTimes = 0; //保存数据的次数
    private int doSaveTimesTwo = 0;//保存数据的次数
    private boolean mSaveDownloadResult = false; //存储数据是否成功

    public DBDAO(Context context) {
        this.mDbHelper = new SQLiteHelper(context);
    }


    /**
     * 获取当前用户的全部下载信息
     *
     * @param userid
     * @return
     */
    public ArrayList<SqlDownloadBean> getAllDownloadBeans(String userid) {
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        ArrayList<SqlDownloadBean> downloadBeenList = new ArrayList<>();
        mDb = mDbHelper.getWritableDatabase();
        Cursor cursor = null;

        try {
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD + " where " + SQLConstants.USERID + " = ? " +
                    " order by "+SQLConstants.POSITION + " asc ",
                    new String[]{userid});
            while (cursor.moveToNext()) {
                SqlDownloadBean bean = new SqlDownloadBean();
                bean.setUserId(cursor.getString(cursor.getColumnIndex(SQLConstants.USERID)));
                bean.setUrl(cursor.getString(cursor.getColumnIndex(SQLConstants.URL)));
                bean.setFileName(cursor.getString(cursor.getColumnIndex(SQLConstants.FILENAME)));
                bean.setDownloadSize(cursor.getLong(cursor.getColumnIndex(SQLConstants.DOWNLOADSIZE)));
                bean.setFileSize(cursor.getLong(cursor.getColumnIndex(SQLConstants.FILESIZE)));
                bean.setFilePath(cursor.getString(cursor.getColumnIndex(SQLConstants.CACHPATH)));
                bean.setDownloadStatus(cursor.getInt(cursor.getColumnIndex(SQLConstants.DOWNLOADSTATUS)));
                downloadBeenList.add(bean);
            }

        } catch (Exception e) {

        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            return downloadBeenList;
        }

    }

    /**
     * 保存需要下载的新对象
     *
     * @param sqlDownloadBean
     */
    public boolean saveNewDownloadBean(SqlDownloadBean sqlDownloadBean) {
        boolean addedTask = isHasAddedTask(sqlDownloadBean.getUrl(), sqlDownloadBean.getUserId());
        if (addedTask) {
            return true; //同一个视频保存一次
        }
        ContentValues cv = new ContentValues();
        cv.put(SQLConstants.USERID, sqlDownloadBean.getUserId());
        cv.put(SQLConstants.FILENAME, sqlDownloadBean.getFileName());
        cv.put(SQLConstants.CACHPATH, sqlDownloadBean.getFilePath());
        cv.put(SQLConstants.DOWNLOADSIZE, sqlDownloadBean.getDownloadSize());
        cv.put(SQLConstants.FILESIZE, sqlDownloadBean.getFileSize());
        cv.put(SQLConstants.DOWNLOADSTATUS, sqlDownloadBean.getDownloadStatus());
        cv.put(SQLConstants.URL, sqlDownloadBean.getUrl());
        cv.put(SQLConstants.TEMPFILEPATH, sqlDownloadBean.getTempFilePath());
        cv.put(SQLConstants.POSITION, sqlDownloadBean.getPosition());
        Cursor cursor = null;
        try {
            mDb = mDbHelper.getWritableDatabase();
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD
                            + " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{sqlDownloadBean.getUserId(), sqlDownloadBean.getUrl()});
            mDb.insert(SQLConstants.TABLENAME_DOWNLOAD, null, cv);
            cursor.close();
            mDb.close();
            mSaveDownloadResult = true;
        } catch (Exception e) {
            doSaveTimes++;
            if (doSaveTimes < 5) { //最多保存5次
                saveNewDownloadBean(sqlDownloadBean);
            } else {
                doSaveTimes = 0;
            }
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            mSaveDownloadResult = false;
        }
        doSaveTimes = 0;
        return mSaveDownloadResult;
    }


    /**
     * 保存对象
     *
     * @param sqlDownloadBean
     */
    public void saveDownloadInf(SqlDownloadBean sqlDownloadBean) {
        ContentValues cv = new ContentValues();
        cv.put(SQLConstants.DOWNLOADSIZE, sqlDownloadBean.getDownloadSize());
        cv.put(SQLConstants.FILESIZE, sqlDownloadBean.getFileSize());
        cv.put(SQLConstants.DOWNLOADSTATUS, sqlDownloadBean.getDownloadStatus());
        Cursor cursor = null;
        try {
            mDb = mDbHelper.getWritableDatabase();
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD
                            + " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{sqlDownloadBean.getUserId(), sqlDownloadBean.getUrl()});
            if (cursor.moveToNext()) {
                mDb.update(SQLConstants.TABLENAME_DOWNLOAD, cv, SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? ",
                        new String[]{sqlDownloadBean.getUserId(), sqlDownloadBean.getUrl()});
            }
            cursor.close();
            mDb.close();

        } catch (Exception e) {
            doSaveTimesTwo++;
            if (doSaveTimesTwo < 5) { //最多保存5次
                saveNewDownloadBean(sqlDownloadBean);
            } else {
                doSaveTimesTwo = 0;
            }
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }

        }
        doSaveTimesTwo = 0;
    }


    /**
     * 判断是否任务已经添加
     *
     * @param url    网络地址
     * @param userid 用户id
     * @return 是否已经添加的结果
     */
    public boolean isHasAddedTask(String url, String userid) {
        boolean isAdded = false;
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        mDb = mDbHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD +
                            " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{userid, url});
            if (cursor.moveToNext()) {
                isAdded = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            return isAdded;
        }

    }


    /**
     * 获取文件名
     *
     * @param userid
     * @param url
     * @return
     */
    public String getFileName(String userid, String url) {
        String fileName = null;
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        mDb = mDbHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD +
                            " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{userid, url});
            if (cursor.moveToNext()) {
                fileName = cursor.getString(cursor.getColumnIndex(SQLConstants.FILENAME));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            return fileName;
        }
    }

    /**
     * 获取文件总大小
     *
     * @param userid
     * @param url
     * @return
     */
    public long getFileSize(String userid, String url) {
        long fileSize = 0;
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        mDb = mDbHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD +
                            " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{userid, url});
            if (cursor.moveToNext()) {
                fileSize = cursor.getLong(cursor.getColumnIndex(SQLConstants.FILESIZE));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            return fileSize;
        }
    }

    /**
     * 获取文件当前下载的状态
     * @return
     */
    public int getFileStatus(String userid , String url){
        int status = 0 ;
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        mDb = mDbHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD +
                            " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{userid, url});
            if (cursor.moveToNext()) {
                status = cursor.getInt(cursor.getColumnIndex(SQLConstants.DOWNLOADSTATUS));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            return status;
        }
    }


    /**
     * 获取已下载文件的大小
     *
     * @param userid
     * @param url
     * @return
     */
    public long getFileDownloadedSize(String userid, String url) {
        long downloadfileSize = 0;
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        mDb = mDbHelper.getWritableDatabase();
        Cursor cursor = null;
        try {
            cursor = mDb.rawQuery("select * from " + SQLConstants.TABLENAME_DOWNLOAD +
                            " where " + SQLConstants.USERID + " = ? and " + SQLConstants.URL + " = ? "
                    , new String[]{userid, url});
            if (cursor.moveToNext()) {
                downloadfileSize = cursor.getLong(cursor.getColumnIndex(SQLConstants.DOWNLOADSIZE));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (cursor != null) {
                cursor.close();
            }
            if (mDb != null) {
                mDb.close();
            }
            return downloadfileSize;
        }

    }

    /**
     * 删除文件
     * @param userid
     * @param url
     * @return
     */
    public boolean deleteFile(String userid,String url){
        boolean  deleteResult = false;
        if (TextUtils.isEmpty(userid)) {
            userid = mDefaultUserid;
        }
        mDb = mDbHelper.getWritableDatabase();
        try {
            mDb.delete(SQLConstants.TABLENAME_DOWNLOAD, SQLConstants.USERID + " = ? and " +
                    SQLConstants.URL + " = ? ", new String[]{userid, url});
            deleteResult = true;
        }catch (Exception e){
            deleteResult = false;
        }finally {

            return deleteResult;
        }
    }

    public void addMd5(){

    }
}
